package com.hsylient.utils;

import com.mysql.cj.jdbc.MysqlDataSource;
import org.apache.commons.dbutils.QueryRunner;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public final class DbUtils {
    
    private static final String USERNAME;
    private static final String PASSWORD;
    private static final String URL;
    private static final String DRIVER;
    
    static {
        InputStream inputStream = DbUtils.class.getClassLoader()
                .getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        USERNAME = properties.getProperty("db.username");
        PASSWORD = properties.getProperty("db.password");
        URL = properties.getProperty("db.url");
        DRIVER = properties.getProperty("db.driver");

    }
    
    public static QueryRunner getQueryRunner() {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setUser(USERNAME);
        mysqlDataSource.setPassword(PASSWORD);
        mysqlDataSource.setUrl(URL);
        return new QueryRunner(mysqlDataSource);
    }


    public static Connection getConnection() {
        Connection connection;
        try {
            Class.forName(DRIVER);
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }
}
